package com.itheima.job.test05;

import java.io.*;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TCPClient {
    public static void main(String[] args) throws IOException {

        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                5,
                10,
                60,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );
        for (int i = 0; i < 10; i++) {
            Socket socket = new Socket("127.0.0.1",12345);
            TCPClientThread tct = new TCPClientThread(socket);
            pool.submit(tct);
        }


    }
}

class TCPClientThread implements Runnable{
    private Socket socket ;
    public TCPClientThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(new FileInputStream("day15_inter\\fj.jpg"));
            OutputStream os = socket.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(os);
            int b ;
            while ((b = bis.read())!=-1){
                bos.write(b);
            }
            bos.flush();
            System.out.println("发送成功");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis!= null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket!=null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
